<?php

namespace App\Http\Controllers\UserApi;

use App\Http\Controllers\Controller;
use App\Services\Api\UserRankExpServices;
use App\Services\Api\VipServices;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Services\Api\EasyWeChatService;
use Illuminate\Support\Facades\Log;

class LoginController extends BaseController
{
    //账号登录接口
    public function login(Request $request,User $user){
        $account_user = $user->where('phone',$request->input('phone'))->first();

        $token = JWTAuth::fromUser($account_user);
        $account_user->token = $token;
        return $account_user;
    }

    //微信登录接口
    public function wx_login(Request $request,User $user){
        try{
            $input = $request->post();
            //Log::info(json_encode($input));die;
            $EasyApp = EasyWeChatService::easy_app();
            $session = $EasyApp->auth->session($input['wx_code']);

            // 说明没有获取到openid
            if(empty($session['openid'])){
                throw new \Exception($session['errmsg']);
            }

            // 查找會員是否存在
            $userObj = $user
                -> where('wx_openid','=',$session['openid'])
                -> first();

            Log::info(json_encode($input).'-------------'.json_encode($session));

            if(empty($userObj)){

//                $decryptedData = $EasyApp->encryptor->decryptData($session['session_key'],$input['wx_iv'],$input['encryptedData']);
//                Log::info(json_encode($decryptedData));
//                if(!key_exists('wx_iv',$input) && !key_exists('encryptedData',$input)){
//                    throw new \Exception('wx_iv和encryptedData必传');
//                }
//                if(empty($decryptedData['avatarUrl'])){
//                    throw new \Exception('解密失败 请检查参数');
//                }

                $user->refresh;

                //头像
                //$avatar = getWxHead($input['avatarUrl']);
                //Log::info('頭像路徑'.$avatar);
                $data['head_img'] = "/upload/head/img.jpg";
                //$data['nickname'] = $input['nickName'];
                $data['wx_openid'] = $session['openid'];
                $data['user_number'] = getRandCode(12);

                $user_id = $user->insertGetId($data);

                $userObj =  $user;

            }else{

                $user_id = $userObj->id;

                //$input['avatarUrl'] = $input['avatarUrl']??'';

                //头像
                //$avatar = getWxHead($input['avatarUrl']);

                //$data['head_img'] = "";
                //$data['nickname'] = $input['nickName']??'';

                //$user->where('id',$user_id)->update($data);

            }

            //记录等级
            self::record_level($user_id);

           /* if($userObj->expire_time <= date("Y-m-d H:i:s")){
                $userObj->total_integral = '过期';
            }*/

            // 自動登錄
            $token = JWTAuth::fromUser($userObj);
            $userObj->token = $token;

            return $this->success($userObj);

        }catch (\Exception $e){
            Log::info('登錄失敗'.$e->getMessage());
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 记录会员等级
     * @param int $user_id
     */
    public static function record_level($user_id = 0)
    {
        $user_rank = (new UserRankExpServices())->get_user_rank($user_id);

        $update['user_rank_id'] = $user_rank['id'];
        $update['user_rank_level'] = $user_rank['level'];
        (new User())->where('id', $user_id)->update($update);
    }
}
